package com.gjy.netty.ag.bio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-05-17 16:58:57
 */
public class TimeServerHandler implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(TimeServerHandler.class);

    private final Socket socket;
    private static final String FORMATTER = "yyyy-MM-dd HH:mm:ss:SSS";

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             InputStreamReader isr = new InputStreamReader(socket.getInputStream());
             BufferedReader in = new BufferedReader(isr)) {
            String currentTime;
            String body;

            while (true) {
                body = in.readLine();
                if (Objects.isNull(body)) {
                    break;
                }
                logger.info("time server receive order: " + body);
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter pattern = DateTimeFormatter.ofPattern(FORMATTER);
                currentTime = "query time order".equalsIgnoreCase(body) ?
                        pattern.format(now) : "bad order";
                out.println(currentTime);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
